import time

# 方法1
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

wd = webdriver.Chrome(service=Service(f".\chromedriver_win136.exe"))
wd.get("https://www.baidu.com")
wd.implicitly_wait(10)
# 注意，旧的教程中会使用find_element_by_id(),这个方法已经被移除
# https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES
# https://selenium-python-zh.readthedocs.io/en/latest/locating-elements.html
element = wd.find_element(By.ID, "kw")
print(element.get_attribute("outerHTML"))
element.send_keys("今天热门")
time.sleep(3)
element.send_keys(Keys.ARROW_DOWN)
element.send_keys(Keys.ARROW_DOWN)
element.send_keys(Keys.ARROW_DOWN)
element.send_keys(Keys.ARROW_DOWN)
time.sleep(3)
element = wd.find_element(By.ID, "su")
element.click()
element.send_keys(Keys.ESCAPE)
time.sleep(5)
print(wd.title)
# time.sleep(4)
# wd.back()
# time.sleep(4)
# wd.forward()
hot_searches = wd.find_elements(By.CLASS_NAME, "toplist1-tr_1MWDu")
print(len(hot_searches))
# 点开始的4个热搜
for h in hot_searches[0:4]:
    h.click()
    time.sleep(5)
# 切换标签
# 获取标签,当前标签是0,前一个是1，前前一个是2,以此类推
window_handles = wd.window_handles
wd.switch_to.window(window_handles[1])
time.sleep(5)
current_url = wd.current_url
print("current_url", current_url)

wd.switch_to.window(window_handles[2])
time.sleep(5)
current_url = wd.current_url
print("current_url", current_url)

wd.switch_to.window(window_handles[3])
time.sleep(5)
current_url = wd.current_url
print("current_url", current_url)

wd.switch_to.window(window_handles[0])
time.sleep(5)
current_url = wd.current_url
print("current_url", current_url)
time.sleep(10)
